<style lang="less">
    @import '../../../styles/common.less';
    @import '../../my-components/data-table/table.less';
</style>

<template>
  <div>
      <Row>
        <Col span="24">
            <Card>
                <p slot="title">
                    <!-- <Icon type="android-more-horizontal"></Icon> -->
                    角色列表
                </p>
                <Row>
                    <Col span="16">
                        <Input placeholder="请输入角色名搜搜..." @on-keyup.enter="handleSearch" v-model="searchData.name" style="width: 150px" />
                        <Button type="primary" shape="circle" icon="ios-search" @click="handleSearch"></Button>
                    </Col>
                    <Col span="3" offset="5" v-if="$hasPerms('role:save')">
                        <span style="margin: 0 10px;">                   
                            <Button type="primary" icon="plus" @click="handleAdd()">新增角色</Button>                          
                        </span>
                    </Col>
                </Row>
                <br>
                <Row>
                    <div class="edittable-table-height-con">
                        <data-table :is-loading="isLoading" v-model="roles" :columns-list="roleColumns"
                                    :total-record="total" :current-page="searchData.pageNum" :permissions-prefix="permsSign"
                            @deleteOne="handleDel" @editOne="handleEdit" @changePage="changePage">
                        </data-table>
                    </div>
                </Row>
            </Card>
        </Col>
      </Row>
      <Modal
            class="autoHeight"
            v-model="addModal"
            :title="modalTitle"
            :closable='false'
            :mask-closable="false">
        <Form ref="addFrom" :model="addFrom" label-position="top" :rules="rules">
            <FormItem label="角色名称" prop="name">
                <Input v-model="addFrom.name"></Input>
            </FormItem>
            <FormItem v-if="admin.id===1" label="公司选择" prop="companyId" required>
                    <Select
                    ref="companyId"
                    placeholder="请输关键词搜索......"
                    v-model="addFrom.companyId"
                    filterable
                    remote
                    :remote-method="remoteCompany"
                    :loading="companyloading">
                    <Option v-for="(con, index) in companies" :value="con.id" :key="index">{{con.name}}</Option>
                </Select>
            </FormItem>
            <FormItem label="备注">
                <Input v-model="addFrom.remark"></Input>
            </FormItem>
            <FormItem label="授权">
                <!-- <Tree ref="perTree" :data="parentMenus" :load-data="loadData" show-checkbox multiple @on-check-change="permsChange"></Tree> -->
                <Tree ref="perTree" :data="parentMenus" show-checkbox multiple @on-check-change="permsChange"></Tree>
            </FormItem>
        </Form>
        <div slot="footer">
            <Button type="text" @click="cancelModal">取消</Button>
            <Button type="primary" :loading="saveLoading" @click="addModalOk">保存</Button>
        </div>
      </Modal>
  </div>

</template>

<script>
import dataTable from '../../my-components/data-table/dataTable.vue';
import roleData from './role_col.js';

export default {
    name: 'role-index',
    components: {
        dataTable
    },
    data () {
        return {
            admin: {},
            companyloading: false,
            companies: [],
            isLoading: true,
            saveLoading: false,
            isAddRole: false,
            permsSign: 'role',
            // 表头
            roleColumns: [],
            // 数据
            roles: [],
            total: 0,
            modalTitle: '',
            addModal: false,
            addFrom: {
                id: 0,
                name: '',
                companyId: '',
                remark: ''
            },
            rules: {
                name: [
                    {required: true, message: '名称不能为空', trigger: 'blur'}
                ],
                companyId: [
                    {required: true, message: '公司不能为空'}
                ]
            },
            parentMenus: [],
            menuList: [],
            // selectPerms: [],
            menuIds: [],
            searchData: {
                name: '',
                pageNum: 1
            }
        };
    },
    methods: {
        getData () {
            this.roleColumns = roleData.roleColumns;
            this.$get('/role/list', this.searchData)
                .then(res => {
                    this.roles = res.records;
                    this.total = res.total;
                    this.searchData.pageNum = res.current;
                    this.isLoading = false;
                })
                .catch(fail => {
                    this.isLoading = false;
                });
        },
        remoteCompany (query) {
            if (query !== '') {
                if (query === 'NAN') { query = '' ;}
                this.companyloading = true;
                this.$post('/company/search', {name: query})
                    .then(res => {
                        this.companyloading = false;
                        this.companies = res;
                    })
                    .catch(fail => {
                        this.companyloading = false;
                    });
            } else {
                this.companyloading = true;
            }
        },
        cancelModal () {
            this.addModal = false;
        },
        handleAdd () {
            this.isAddRole = true;
            this.modalTitle = '添加角色';
            this.menuIds = [];
            // this.selectPerms = [];
            this.getMenus();
        },
        handleEdit (val) {
            this.isAddRole = false;
            // 获取当前角色的权限树和权限
            this.$get('/role/info/' + val.id)
                .then(res => {
                    this.modalTitle = '编辑角色';
                    this.addFrom.id = res.id;
                    this.addFrom.companyId = res.companyId;
                    this.addFrom.name = res.roleName;
                    this.addFrom.remark = res.remark;
                    // this.parentMenus = res.rolePerms;
                    this.menuIds = res.menuIdList; // 角色权限列表
                    // this.selectPerms = res.perms ? res.perms.split(',') : [];
                    this.getMenus();
                }).catch(error => {
                    console.log(error);
                    this.$Message.error('获取角色信息失败');
                });
        },
        addModalOk () {
            this.$refs.addFrom.validate((valid) => {
                if (valid) {
                    let url = '/role/update';
                    if (this.isAddRole) {
                        url = '/role/save';
                    }
                    this.saveLoading = true;
                    this.$post(url, {
                        id: this.addFrom.id === 0 ? null : this.addFrom.id,
                        roleName: this.addFrom.name,
                        remark: this.addFrom.remark,
                        companyId: this.addFrom.companyId || JSON.parse(localStorage.admin).companyId,
                        // perms: this.selectPerms.toString(),
                        menuIdList: this.menuIds
                    }, 'json')
                        .then(res => {
                            this.getData();
                            this.$Message.success('操作成功');
                            this.addModal = false;
                            this.saveLoading = false;
                        })
                        .catch(error => {
                            this.saveLoading = false;
                            this.$Message.error(error.message);
                        });
                } else {
                    this.saveLoading = false;
                    // 获取表单域所有field
                    let fields = this.$refs.addFrom.fields;
                    // 聚焦错误表单域
                    try {
                        fields.forEach(element => {
                            if (element.validateState === 'error') {
                                // 这里的element无foucs()
                                let refName = element.prop;
                                this.$refs[refName].focus();
                                // 抛出异常跳出循环
                                foreach.break = new Error('StopIteration');
                            }
                        });
                    } catch (e) {
                        console.log(e);
                    }
                }
            });
        },
        handleDel (val, index) {
            // 删除
            let roleIds = [];
            roleIds.push(val.id);
            this.$del('/role/delete',
                roleIds, 'json'
            ).then(res => {
                this.roles.splice(index, 1);
                this.$Message.success('删除了' + val.roleName);
            }).catch(error => {
                console.log(error);
                this.$Message.error(error.message);
            });
        },
        handleSelectAll (status) {
            // this.$manager.selection.selectAll(status);
        },
        changePage (val) {
            this.searchData.pageNum = val;
            this.getData();
        },
        permsChange (data) {
            // let checkedNode = this.$refs.perTree.getCheckedNodes(); 点击文字方可获取
            let arr = [];
            if (data.length > 0) {
                // let menu = [];
                data.forEach(element => {
                // 收集含perms的即为选择的权限
                    if (element.perms && (arr.indexOf(element.id) === -1)) {
                        // this.selectPerms.push(element.perms);
                        arr.push(element.id);
                        // menu.push(element);
                    }
                });
                this.menuIds = arr;
                // this.collectMenuIds(menu);
            } else {
                // this.selectPerms = [];
                this.menuIds = [];
            }
            // console.log(this.selectPerms);
            // console.log(this.menuIds);
        },
        getMenus () {
            this.$get('/menu/list')
                .then(res => {
                    this.menuList = res;
                    if (localStorage.admin && localStorage.access) { // 只能分配自己拥有的权限
                        if (JSON.parse(localStorage.admin).id !== 1) {
                            let accessList = localStorage.access.split(',');
                            // console.log(accessList);
                            this.menuList = res.filter(r => {
                                return (r.type !== 3) || (accessList.indexOf(r.perms) > -1);
                            });
                            // console.log(this.menuList);
                        }
                    }
                    this.getParentMenus();
                })
                .catch(fail => {
                    this.$Message.error('获取菜单失败');
                });
        },
        getParentMenus () {
            let menuTemp = this.menuList.filter(item => { // 添加目录
                return item.type === 1;
            });
            menuTemp.forEach(el => {
                el.children = this.getChildrenMenu(el.id); // 添加菜单
                el.children.forEach(r => {
                    r.children = this.getChildrenMenu(r.id); // 添加按钮
                });
            });
            this.parentMenus = menuTemp.filter(item => { // 过滤空菜单
                if (!item.children.length) {
                    return false;
                } else {
                    for (let i = item.children.length - 1; i >= 0; i--) {
                        if (!item.children[i].children.length) {
                            item.children.splice(i, 1); // 移除空菜单
                        }
                    }
                    if (!item.children.length) { return false; } // 移除空目录
                }
                return true;
            }); // 过滤空菜单
            this.addModal = true;
        },
        getParentMensByMenu (menu) {
            let pmenu = {};
            this.menuList.forEach(item => {
                if (item.id === menu.parentId) {
                    pmenu = item;
                }
            });
            return pmenu;
        },
        getChildrenMenu (parentId) {
            let childrens = [];
            this.menuList.forEach((item, index) => {
                if (item.parentId === parentId) { // 查找子级
                    if (this.menuIds.length > 0 && item.type === 3 && this.menuIds.indexOf(item.id) > -1) {
                        item.checked = true;
                    }
                    childrens.push(item);
                }
            });
            return childrens;
        },
        collectMenuIds (btnMenus) {
            btnMenus.forEach(item => {
                let pmenu = this.getParentMensByMenu(item);
                if (this.menuIds.indexOf(pmenu.id) === -1) {
                    this.menuIds.push(pmenu.id);
                }
                if (this.menuIds.indexOf(pmenu.parentId) === -1) {
                    this.menuIds.push(pmenu.parentId);
                }
            });
        },
        loadData (item, callback) {
            callback(this.getChildrenMenu(item.id));
        },
        handleSearch () {
            this.searchData.pageNum = 1;
            this.getData();
        }
    },
    created () {
        this.getData();
        this.remoteCompany('NAN');
        this.admin = JSON.parse(localStorage.admin);
    }
};
</script>
